<?php
class HotelPermissionForm extends Form
{
	var $hotel = false;
	
    function HotelPermissionForm()
    {
        Form::Form("HotelPermissionForm");
        
        $this->link_css("style/hotel.css");
        
        $id 		= Url::get("id");
        
        if($id)
        {
        	$this->hotel = Db_Hotel::getHotelById($id);
        }
        
        if(!$this->hotel)
        {
        	Url::redirect_current();
        }
        
        //Check quyền
		if(!User::have_permit("hotel_edit"))
        {
        	if(!Db_Hotel::have_permit_manage($this->hotel, User::id()))
	        {
	        	Url::access_denied();
	        }
        }
        #############################################################################
        
        $pmid = Url::getInt('pmid');
        
        switch (Url::get('act'))
        {
        	case 'disable':
        		if($pmid)
        		{
        			$pmis = DB::select('hotel_user',"id=$pmid");
        			
        			if($pmis && $pmis['status'] == 1 && $pmis['hotel_id'] == $this->hotel['id'])
        			{
        				DB::query("UPDATE hotel_user SET status=2, user_m=".User::id() . ", time_m=" . TIME_NOW . " WHERE id={$pmis['id']}");
        			}
        			
        			if(!DB::select("hotel_user","hotel_id={$this->hotel['id']} AND user_id=" . $pmis['user_id'] . " AND status=1"))
        			{
        				$uids = $this->hotel['user_ids'];
        				
	        			if($uids != '' && $uids != '0')
	        			{
	        				if(strpos($uids,"_{$pmis['user_id']}_") !== false)
	        				{
	        					$uids = str_replace("_{$pmis['user_id']}_","_",$uids);
	        					
	        					if($uids == "_")
	        					{
	        						$uids = '';
	        					}
	        				}
	        			}
	        			else
	    				{
	    					$uids = '';
	    				}
	    				
	    				DB::update('hotel', array('user_ids'=> $uids ), "id={$this->hotel['id']}");
    				}
        		}
        		
        		Url::redirect_current(array('cmd','id'));
        		break;
        	case 'enable':
        		if($pmid)
        		{
        			$pmis = DB::select('hotel_user',"id=$pmid");
        			
        			if($pmis && $pmis['status'] == 2 && $pmis['hotel_id'] == $this->hotel['id'])
        			{
        				DB::query("UPDATE hotel_user SET status=2, user_m=".User::id() . ", time_m=" . TIME_NOW . " WHERE hotel_id={$this->hotel['id']} AND user_id={$pmis['user_id']} AND status=1");
        				DB::query("UPDATE hotel_user SET status=1, user_m=".User::id() . ", time_m=" . TIME_NOW . " WHERE id={$pmis['id']}");
        			}
        			
        			$uids = $this->hotel['user_ids'];
        			
        			if($uids != '' && $uids != '0')
        			{
        				if(strpos($uids,"_{$pmis['user_id']}_") === false)
        				{
        					$uids = str_replace("_{$pmis['user_id']}_","_",$uids);
        					
        					$uids .= ($uids != ''? "" : "_") . $pmis['user_id'] . "_";
        				}
        			}
        			else
    				{
    					$uids = "_" . $pmis['user_id'] . "_";
    				}
        			
    				DB::update('hotel', array('user_ids'=>$uids), "id={$this->hotel['id']}");
        		}
        		
        		Url::redirect_current(array('cmd','id'));
        		break;
        	case 'delete':
        		if($pmid)
        		{
        			$pmis = DB::select('hotel_user',"id=$pmid");
        			
        			if($pmis && $pmis['status'] != -1 && $pmis['hotel_id'] == $this->hotel['id'])
        			{
        				DB::query("UPDATE hotel_user SET status=-1, user_m=".User::id() . ", time_m=" . TIME_NOW . " WHERE id={$pmis['id']}");
        			}
        			
        			if(!DB::select("hotel_user","hotel_id={$this->hotel['id']} AND user_id=" . $pmis['user_id'] . " AND status=1"))
        			{
        				$uids = $this->hotel['user_ids'];
        				
	        			if($uids != '' && $uids != '0')
	        			{
	        				if(strpos($uids,"_{$pmis['user_id']}_") !== false)
	        				{
	        					$uids = str_replace("_{$pmis['user_id']}_","_",$uids);
	        					
	        					if($uids == "_")
	        					{
	        						$uids = '';
	        					}
	        				}
	        			}
	        			else
	    				{
	    					$uids = '';
	    				}
	    				
	    				DB::update('hotel', array('user_ids'=> $uids ), "id={$this->hotel['id']}");
    				}
        		}
        		
        		Url::redirect_current(array('cmd','id'));
        		break;
        	default:
                
        }
    }
    
    function on_submit()
    {
		$user_email = Url::get("user_email");
		$user_id 	= Url::getInt("user_id");
		
		$user = array();
		
		
		if(($user_email == '' || !preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$/i",$user_email)) && $user_id<=0)
		{
			$this->setFormError('user_email',"Bạn chưa nhập thông tin Tài khoản!");
			return ;
		}
		
		if($user_email != '')
		{
			$user = Db_User::getUsersByEmail($user_email);
		}
		
		if(!$user)
		{
			if($user_id)
			{
				$user = User::getUser($user_id);
			}
		}
		
		if(!$user)
		{
			$this->setFormError('user_email',"Tài khoản không tồn tại!");
			return ;
		}
		
		$user_id = $user['id'];
		
		if(!DB::select("hotel_user","hotel_id={$this->hotel['id']} AND user_id=$user_id AND status=1"))
        {
			$uids = $this->hotel['user_ids'];
	        			
			if($uids != '' && $uids != '0')
			{
				if(strpos($uids,"_{$user_id}_") === false)
				{
					$uids = str_replace("_{$user_id}_","_",$uids);
					
					$uids .= ($uids != ''? "" : "_") . $user_id . "_";
				}
			}
			else
			{
				$uids = "_{$user_id}_";
			}
			
			DB::update('hotel', array('user_ids'=>$uids), "id={$this->hotel['id']}");
			
			DB::insert("hotel_user", array(
											"hotel_id" 	=> $this->hotel['id'],
											"user_id" 	=> $user_id,
											"user_add" 	=> User::id(),
											"user_m" 	=> User::id(),
											"time_c" 	=> TIME_NOW,
											"time_m" 	=> TIME_NOW,
											"status" 	=> 1
											));
											
			Url::redirect_current(array('cmd','id'));
	    }
	    else 
	    {
			$this->setFormError('user_email',"Tài này đã được phân quyền quản lý Khách sạn này rồi!");
			return ;
		}
    }

    function draw()
    {
        global $display;
        $display->add("WEB_ROOT",WEB_ROOT);
        $display->add("WEB_DIR",WEB_DIR);
        
        $this->beginForm(true);
        
        $hotel 		= $this->hotel;
        
        $hotel['name'] 		= stripslashes($hotel['name']);
        $hotel['desc'] 		= stripslashes($hotel['desc']);
        $hotel['address'] 	= stripslashes($hotel['address']);
        $hotel['address'] 	= stripslashes($hotel['address']);
        
        $status_arr= array(1=>"Hiện",2=>"Ẩn");
       
        $hotel['status'] = $status_arr[$hotel['status']];
        
        $display->add('hotel', 			$hotel);
        
        $uid_arr = array();
        
        if($hotel['user_ids'])
        {
        	$arr = explode("_", $hotel['user_ids']);
        	
        	if($arr)
        	{
        		$uid_arr = array_flip($arr);
        		
        		if(isset($uid_arr['']))
        		unset($uid_arr['']);
        	}
        }
        
        $manage_user1s 	= array();
        $manage_user2s 	= array();
        $uids_arr 		= array();
        
        if(User::have_permit('admin_hotel'))
        {
        	$re = DB::query("SELECT * FROM hotel_user WHERE hotel_id={$this->hotel['id']} ORDER BY id DESC");
        }
        else
        {
        	$re = DB::query("SELECT * FROM hotel_user WHERE hotel_id={$this->hotel['id']} AND status > 0 ORDER BY id DESC");
        }
        
        $status_arr= array(
        					1	=>	"<font color='green'>OK</font>",
        					2	=>	"<font color='brown'>Disabled</font>",
        					-1	=>	"<font color='red'>Đã xóa</font>"
        					);
        
        $uids_arr_check = $uid_arr;
        $ids_arr_check 	= array();
        
        if($re)
        {
        	while($user = mysql_fetch_assoc($re))
        	{
        		$uids_arr[$user['user_id']] 	= $user['user_id'];
        		$uids_arr[$user['user_add']] 	= $user['user_add'];
        		$uids_arr[$user['user_m']] 		= $user['user_m'];
        		$uids_arr[$user['user_del']] 	= $user['user_del'];
        		
        		if(!isset($uid_arr[$user['user_id']]) && $user['status'] == 1)
        		{
        			$user['status']			= 2;
        			$user['status_str']		= $status_arr[2];
        			
        			$ids_arr_check[$user['id']] = $user['id'];
        			
        			$manage_user2s[$user['id']] = $user;
        		}
        		else
        		{
        			$status 			= $user['status'];
        			$user['status_str']	= $status_arr[$user['status']];
        			
        			if($status == 1)
        			{
        				$manage_user1s[$user['id']] = $user;
        			}
        			else
        			{
        				$manage_user2s[$user['id']] = $user;
        			}
        		}
        		
        		if(isset($uid_arr[$user['user_id']]) && isset($uids_arr_check[$user['user_id']]))
        		{
        			unset($uids_arr_check[$user['user_id']]);
        		}
        	}
        }
        
        if(isset($uids_arr[0])) unset($uids_arr[0]);
        
        //Cập nhật trạng thái các bản ghi
        if($ids_arr_check)
        {
        	DB::query("UPDATE hotel_user SET status=2 WHERE id IN(" . implode(',', $ids_arr_check) . ")");
        }
        
        //Cập nhật phân quyền lại cho KS
        if($uids_arr_check)
        {
        	foreach ($uids_arr_check as $uid=>$val)
        	{
        		unset($uid_arr[$uid]);
        	}
        	
        	if($uid_arr)
        	{
        		$uids = "_" . implode('_', array_keys($uid_arr)) . "_";
        	}
        	else
        	{
        		$uids = '';
        	}
        	
        	DB::update('hotel', array('user_ids'=>$uids), "id={$this->hotel['id']}");
        }
        
        $all_users = array();
        
        if($uids_arr)
        {
        	$all_users = Db_User::getUsersByIDs(Url::check_ids(implode(',',$uids_arr)));
        }
        
        $manage_users = $manage_user1s + $manage_user2s;
        
        if($manage_users)
        {
        	foreach ($manage_users as &$user)
        	{
        		if($user['time_c'] != $user['time_m'])
        		{
        			$user['time_m'] = '<br />Sửa lúc: ' . date('d/m/y H:i:s', $user['time_m']) . " bởi [{$user['user_m']}] " . @$all_users[$user['user_m']]['email'];
        		}
        		else
        		{
        			$user['time_m'] = '';
        		}
        		
        		if($user['time_c'])
        		{
        			$user['time_c'] = 'Tạo lúc: ' . date('d/m/y H:i:s', $user['time_c']) . " bởi [{$user['user_add']}] " . @$all_users[$user['user_m']]['email'] . " {$user['time_m']}";
        		}
        		
        		if($user['status'] == -1 && $user['time_del'])
        		{
        			$user['time_c'] .= '<br /><font color=red>Xóa lúc: ' . date('d/m/y H:i:s', $user['time_del']) . " bởi [{$user['user_del']}] " . @$all_users[$user['user_del']]['email'];
        		}
        		
        		$user['user_id'] = "[{$user['user_id']}] ". @$all_users[$user['user_id']]['email'];
        	}
        }
        
        $display->add("manage_users",$manage_users);
        
        $display->add("msg",$this->showFormErrorMessages(1));
        
        $display->add("user_email", Url::get("user_email"));
        
        if(Url::getInt("user_id"))
        	$display->add("user_id", 	Url::getInt("user_id"));
        else
       	 	$display->add("user_id", 	'');
        
        $display->output("HotelPermission");
            
        $this->endForm();
    }
}
?>